//
//  YZMConfigureService.m
//  YZMicroStock
//
//  Created by wangminhong on 16/4/14.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMConfigureService.h"
#import "YZMSeverTimeService.h"
#import "YZClient.h"
#import "YZMLimitStockModel.h"

#import <DateTools/DateTools.h>
#import "YZClient+FreeExperience.h"

@interface YZMConfigureService()

@property (nonatomic, strong) NSArray *limitStockList;

@end

@implementation YZMConfigureService

+ (YZMConfigureService *)sharedServiceWithTradeType:(YZM_TRADE_TYPE)tradeType {
    
    switch (tradeType) {
        case YZM_TRADE_TYPE_FOR_A_STOCK: {
            return [YZMConfigureService sharedService];
        }
            
        case YZM_TRADE_TYPE_FOR_A_STOCK_D: {
            return [YZMTDConfigureService sharedService];
        }
        case YZM_TRADE_TYPE_FOR_A_STOCK_ONE: {
            return [YZMONEConfigureService sharedService];
        }
        case YZM_TRADE_TYPE_FOR_A_STOCK_FREE:{
            return [YZMFreeExperienceConfigureService sharedService];
        }
        case YZM_TRADE_TYPE_FOR_A_STOCK_SIM:{
            return [YZMSIMUConfigureService sharedService];
        }
        case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:{
            return [YZMYLBConfigureService sharedService];
        }
        default:
            return nil;
    }
}

+ (instancetype)sharedService
{
    static YZMConfigureService *sInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sInstance = [[self alloc] init];
    });
    
    return sInstance;
}

- (instancetype)init{
    
    self = [super init];
    if (self) {
        
        //获取默认配置参数
        self.tradeType = YZM_TRADE_TYPE_FOR_A_STOCK;
        self.defaultConfigure = [YZMConfigureModel createDecoder];
        self.limitStockList= [NSArray array];
    }
    return self;
}

- (BOOL)isInLimitStockListWithStockCode:(NSString *)stockCode{
    
    if (self.limitStockList.count == 0) {
        
        return NO;
    }
    
    for (YZMLimitStockModel *model in self.limitStockList) {
        
        if ([model.code isEqualToString:stockCode]) {
            
            return YES;
        }
    }
    
    return NO;
}

/*判断递延费是否显示*/
- (BOOL)isInTradeShowTimePeriods{
    
    if (!self.defaultConfigure) {
        
        return YES;
    }
    
    return [self.defaultConfigure isInTradeShowTimePeriods];
}

/*判断是否可交易*/
- (BOOL)isInTradeTimePeriods{
    
    if (!self.defaultConfigure) {
        
        return YES;
    }
    
    return [self.defaultConfigure isInTradeTimePeriods];
}

/*进入点买首页时，判断是否需要重新获取配置参数，主要包括交易时间和默认股票，按照每天早上8点更新的原则*/
- (void)checkIfNeedRequestConfigureWithSuccess:(void (^)())sucess{
    
    NSDate *serverTime = [YZMSeverTimeService sharedService].severDate;
    
    if (!self.defaultConfigure || !self.defaultConfigure.requestTime) {
        //首次进入还未获取过配置参数 或者 重新启动App时 默认需要获取一次
        [self fetchConfigureDataSuccess:sucess failure:nil];
        [self fetchLimitStockListSuccess:nil failure:nil];
        return;
    }
    
    if ( (self.defaultConfigure.requestTime.hour <9 && serverTime.hour >9) || [[serverTime dateBySubtractingHours:4] isLaterThan:self.defaultConfigure.requestTime] ) {
        
        //默认四个小时需要更新一次 且当配置获取时间小于9点，而系统时间大于9点时，再获取一次。
        [self fetchConfigureDataSuccess:sucess failure:nil];
        [self fetchLimitStockListSuccess:nil failure:nil];
        return;
    }
    
    if (sucess) {
        sucess();
    }
}

- (void)fetchLimitStockListSuccess:(void (^)())sucess failure: (void (^)(NSError *error))failure{
    
    [YZClient td_getLimitStockListSuccess:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            self.limitStockList = topModel.data;
            
        }else{
        
            if (failure) {
                
                failure([NSError yz_errorWithBadResponse]);
            }
        }
        
    } failure:^(NSError *error) {
        if (failure) {
            
            failure(error);
        }
    }];
}

- (void)fetchConfigureDataSuccess:(void (^)())success failure: (void (^)(NSError *error))failure{
    
    switch (self.tradeType) {
        case YZM_TRADE_TYPE_FOR_A_STOCK: {
            
            [YZClient td_getConfigureDataSuccess:^(NSURLResponse *response, id responseObject) {
                
                YZGeneralResultModel *topModel = responseObject;
                if (topModel.success) {
                    
                    YZMConfigureModel *model = topModel.data;
                    if (!self.defaultConfigure || ![self.defaultConfigure.version isEqualToString:model.version]) {
                        
                        //保存基础参数
                        [model createEncoder];
                    }
                    self.defaultConfigure = model;
                    if (success) {
                        
                        success();
                    }
                }else{
                    if (failure) {
                        failure([NSError yz_errorWithBadResponse]);
                    }
                }
                
            } failure:^(NSError *error) {
                
                if (failure) {
                    failure(error);
                }
            }];
        }
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_D: {
            [YZClient td_fecthTradeRiskWithsuccess:^(NSURLSessionDataTask *task, id responseObject) {
                YZGeneralResultModel *topModel = responseObject;
                if (topModel.success) {
                    YZMConfigureModel *model = topModel.data;
                    if (!self.defaultConfigure || ![self.defaultConfigure.version isEqualToString:model.version]) {
                        //保存基础参数
                        [model createEncoder];
                    }
                    self.defaultConfigure = model;
                    if (success) {
                        success();
                    }
                }else{
                    if (failure) {
                        failure([NSError yz_errorWithBadResponse]);
                    }
                }
            } failure:^(NSError *error) {
                if (failure) {
                    failure(error);
                }
            }];
        }
            break;

        case YZM_TRADE_TYPE_FOR_A_STOCK_ONE: {
            [YZClient oneY_getConfigureDataSuccess:^(NSURLResponse *response, id responseObject) {
                YZGeneralResultModel *topModel=responseObject;
                if (topModel.success) {
                    YZMConfigureModel *model=topModel.data;
                    if (!self.defaultConfigure || ![self.defaultConfigure.version isEqualToString:model.version]) {
                        [model createEncoder];
                    }
                    self.defaultConfigure=model;
                    if (success) {
                        success();
                        }
                    }else{
                        if (failure) {
                            failure([NSError yz_errorWithBadResponse]);
                        }
                    }
            } failure:^(NSError *error) {
                if (failure) {
                    failure(error);
                }
            }];
        }
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_FREE:{
            [YZClient freeEx_getConfigureDataSuccess:^(NSURLResponse *response, id responseObject) {
                YZGeneralResultModel *topModel=responseObject;
                if (topModel.success) {
                    YZMFreeExperienceConfigureModel *model=topModel.data;
                    if (!self.defaultConfigure || ![self.defaultConfigure.version isEqualToString:model.version]) {
                        [model createEncoder];
                    }
                    self.defaultConfigure=model;
                    if (success) {
                        success();
                    }
                }else{
                    if (failure) {
                        failure([NSError yz_errorWithBadResponse]);
                    }
                }
            } failure:^(NSError *error) {
                if (failure) {
                    failure(error);
                }
            }];

        }
            break;
            
        case YZM_TRADE_TYPE_FOR_A_STOCK_SIM: {
            
            [YZClient simU_getConfigureDataSuccess:^(NSURLResponse *response, id responseObject) {
                YZGeneralResultModel *topModel = responseObject;
                if (topModel.success) {
                    
                    YZMConfigureModel *model = topModel.data;
                    if (!self.defaultConfigure || ![self.defaultConfigure.version isEqualToString:model.version]) {
                        
                        //保存基础参数
                        [model createEncoder];
                    }
                    self.defaultConfigure = model;
                    if (success) {
                        
                        success();
                    }
                }else{
                    if (failure) {
                        failure([NSError yz_errorWithBadResponse]);
                    }
                }
            } failure:^(NSError *error) {
                if (failure) {
                    failure(error);
                }
            }];
        }
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:{
            [YZClient td_getYLBConfigureDataSuccess:^(NSURLResponse *response, id responseObject) {
                
                YZGeneralResultModel *topModel = responseObject;
                if (topModel.success) {
                    
                    YZMConfigureModel *model = topModel.data;
                    if (!self.defaultConfigure || ![self.defaultConfigure.version isEqualToString:model.version]) {
                        
                        //保存基础参数
                        [model createEncoder];
                    }
                    self.defaultConfigure = model;
                    if (success) {
                        
                        success();
                    }
                }else{
                    if (failure) {
                        failure([NSError yz_errorWithBadResponse]);
                    }
                }
                
            } failure:^(NSError *error) {
                
                if (failure) {
                    failure(error);
                }
            }];
        }
            
        default:
            break;
    }
}

@end

@implementation YZMTDConfigureService
+ (instancetype)sharedService
{
    static YZMTDConfigureService *sInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sInstance = [[self alloc] init];
    });
    return sInstance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        //获取默认配置参数
        self.tradeType = YZM_TRADE_TYPE_FOR_A_STOCK_D;
        self.defaultConfigure = [YZMTDConfigureModel createDecoder];
        self.limitStockList= [NSArray array];
    }
    return self;
}
@end

@implementation YZMYLBConfigureService

+ (instancetype)sharedService
{
    static YZMYLBConfigureService *sInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sInstance = [[self alloc] init];
    });
    return sInstance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        //获取默认配置参数
        self.tradeType = YZM_TRADE_TYPE_FOR_A_STOCK_YLB;
        self.defaultConfigure = [YZMYLBConfigureModel createDecoder];
        self.limitStockList= [NSArray array];
    }
    return self;
}

@end

@implementation YZMONEConfigureService
+ (instancetype)sharedService
{
    static YZMONEConfigureService *sInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sInstance = [[self alloc] init];
    });
    return sInstance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        //获取默认配置参数
        self.tradeType = YZM_TRADE_TYPE_FOR_A_STOCK_ONE;
        self.defaultConfigure = [YZMONEConfigureModel createDecoder];
        self.limitStockList= [NSArray array];
    }
    return self;
}

@end

@implementation YZMSIMUConfigureService

+ (instancetype)sharedService
{
    static YZMSIMUConfigureService *sInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sInstance = [[self alloc] init];
    });
    return sInstance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        //获取默认配置参数
        self.tradeType = YZM_TRADE_TYPE_FOR_A_STOCK_SIM;
        self.defaultConfigure = [YZMSIMUConfigureModel createDecoder];
        self.limitStockList= [NSArray array];
    }
    return self;
}


@end

@implementation YZMFreeExperienceConfigureService


+ (instancetype)sharedService
{
    static YZMFreeExperienceConfigureService *sInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sInstance = [[self alloc] init];
    });
    return sInstance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        //获取默认配置参数
        self.tradeType = YZM_TRADE_TYPE_FOR_A_STOCK_FREE;
        self.defaultConfigure = [YZMFreeExperienceConfigureModel createDecoder];
        self.limitStockList= [NSArray array];
    }
    return self;
}


@end
